<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class GoodsType extends Model
{
    /**
     * 定义主键字段
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 定义表名，不含前缀
     *
     * @var string
     */
    protected $table      = 'wd_goods_type';

    /**
     * 定义拒绝保存的字段
     *
     * @var array
     */
    protected $guarded    = ['id'];

    /**
     * 开启laravel默认的时间记录
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 自连接
     *
     * @return void
     */
    public function sub_type()
    {
        return $this->hasMany('App\Models\GoodsType', 'pid', 'id');
    }

    public function goods()
    {
        return $this->hasMany('App\Models\Goods', 'goods_type_id', 'id');
    }

    /**
     * 商品的分类信息
     *
     * @return void
     */
    public static function type_info( $name )
    {
        $data = self::with(['sub_type' => function ( $query ) {

            $query->with(['goods' => function ( $query ) {

                $query->select(DB::raw('count("id") as num, goods_type_id, status'))->groupBy('status')->groupBy('goods_type_id');

            }])->select('id', 'pid', 'name', 'app_pic', 'status', 'sort', 'note');

         }])->where('pid', 0)

            ->select('id', 'pid', 'name', 'app_pic', 'status', 'sort', 'note')

            ->orderBy('sort')

            ->get();
      
        $return_data = [];

        if ( $name ) {
            foreach ($data as $k => $v) {
                if ( false !== strpos($v['name'], $name )) {
                    $return_data[] = $v;
                } else {
                    foreach ($v['sub_type'] as $k1 => $v1) {
                        if ( false !== strpos($v1['name'], $name )) {
                            $return_data[] = $v;
                            break;
                        }
                    }
                }
            }
        }

        return $name?$return_data:$data;
    }

  

}
